<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;

class LoginMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!session('info') && !Cookie::get('info')) {
            return redirect('/admin/login/index');
        }
        if($info = Cookie::get('info')){
            $info = json_decode($info, true);
            $data = DB::table('users')->find($info['id']);
            $data = json_decode(json_encode($data), true);
            // 符合条件自动登录
            if(md5($info['password']) == $data['password'] && !session('info'))
            {
                unset($data['password']);
                session(["info" => $data]);
            }
        }
        return $next($request);
    }
}
